<script setup>
import { reactive, ref,onMounted } from 'vue';
import {ElLoading, ElMessage} from 'element-plus'
import { useRouter } from 'vue-router'
// import { adminStore, tokenStore } from '../store/store.js';
// // 引入axios编写api
import loginApi from '../api/login.js'
import {Briefcase, User, UserFilled} from "@element-plus/icons-vue";
import captchaApi from "@/api/captcha.js";
// import captchaApi from '../api/captcha.js';

//登录表单数据
const form = ref({
  name:'',
  real_name:'',
  gender:'',
  phone: '',
  password: '',
  captcha: '',
  key: '',
  image:'',
  username:'',
  role:'user' //默认用户角色
});
onMounted(function(){
  // 加载验证码
  loadCaptcha();
})

//角色切换
const roles=[
  {value:'admin',label:'管理员登录'},
  {value:'user',label:'用户登录'}
];
const activeRole=ref('user');

// 获取路由对象
const router = useRouter();

// 验证码图片数据
const captcha = ref("");

// 加载验证码
const loadCaptcha=async ()=>{
    const res=await captchaApi.captcha();
    form.value.key=res.key;
    captcha.value=res.base;
}

//切换角色
const handleRoleChange=(role)=>{
  form.value.role=role;
  activeRole.value=role;
  //切换角色时重置表单
  if(role==='user') {
    form.value.username = '';
  }else {
    form.value.name = '';
  }
  form.value.password='';
  form.value.captcha='';
  loadCaptcha(); //重新加载验证码
}

//登录提交
const onSubmit = async () => {
  // const res = await loginApi.loginadmin(form.value);
  // if(res){
  //   localStorage.setItem("token",res);
  //   //跳转
  //   router.push('/');
  // }

  //表单验证
  if (form.value.role === 'user' &&!form.value.username) {
    ElMessage.warning('请输入用户名');
    return;
  }
  if (form.value.role === 'admin' &&!form.value.name) {
    ElMessage.warning('请输入管理员名');
    return;
  }
  if (!form.value.password) {
    ElMessage.warning('请输入密码');
    return;
  }
  if (!form.value.captcha) {
    ElMessage.warning('请输入验证码');
    return;
  }

  //显示加载动画
  const loading=ElLoading.service({
    lock: true,
    text: '登录中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    let res;
    // 根据角色调用对应后端接口
    if (form.value.role === 'user') {
      // 用户登录：传递user_name、password、captcha、key
      res = await loginApi.userdologin({
        username: form.value.username,
        password: form.value.password,
        captcha: form.value.captcha,
        key: form.value.key
      });
    } else {
      // 管理员登录：传递clerk_name、password、captcha、key
      res = await loginApi.admindologin({
        name: form.value.name,
        password: form.value.password,
        captcha: form.value.captcha,
        key: form.value.key
      });
    }
    console.log('接口',res);


    if(res) {
      //存储登录信息
      localStorage.setItem("token", res);
      localStorage.setItem("role", form.value.role);
      localStorage.setItem('username',
          form.value.role === 'user' ? form.value.username : form.value.name);

      //根据角色跳转不同页面
      if (form.value.role === 'user') {
        // router.push('/user/index');//用户首页
        router.push('/user/index');
      } else {
        router.push('/admin/index');//管理员首页
      }
      ElMessage.success(`登录成功,${form.value.username}`);
    } else {
      // 接口返回但状态码不正确（如验证码错误）
      ElMessage.error(res?.msg || '登录失败，请重试');
      loadCaptcha(); // 刷新验证码
     }
    } catch (error){
    // 处理接口异常
    // const errorMsg = error.response?.data?.msg || '网络异常，登录失败';
    ElMessage.error(errorMsg);
    loadCaptcha(); // 异常时刷新验证码
    console.error('登录接口错误：', error);
  }finally {
    loading.close();
  }
};

</script>


<template>

  <div class="login-container">

<!--    背景装饰-->
    <div class="login-bg"></div>
    <div class="login-bg-overlay"></div>

<!--    登录卡片-->
    <div class="login-card">

      <!-- 品牌区域 -->
      <div class="login-brand">
        <img src="@/assets/logo.png" alt="系统logo" class="brand-logo">
        <h1 class="brand-title">抢票系统</h1>
      </div>

      <!-- 角色选择器 -->
      <div class="role-selector">
      <div
          v-for="role in roles"
          :key="role.value"
          @click="handleRoleChange(role.value)"
          :class="['role-item', activeRole === role.value ? 'role-active' : '']"
      >
        <component :is="role.icon" class="role-icon"></component>
        <span class="role-label">{{ role.label }}</span>
      </div>
      </div>


<!-- 登录表单-->
    <el-form class="login-from" :model="form">



<!--      用户名-->
      <el-form-item>
        <el-input v-model="form.username"
                  v-if="form.role === 'user'"
                  placeholder="请输入用户名"
                  :prefix-icon="UserFilled"
                  maxlength="20"
                  class="form-input"></el-input>
        <el-input
            v-model="form.name"
            v-else
            placeholder="请输入管理员名"
            :prefix-icon="Briefcase"
            maxlength="20"
            class="form-input"
        />
      </el-form-item>

<!--      密码-->
      <el-form-item>
        <el-input v-model="form.password"
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
                  maxlength="20"
                  class="form-input"></el-input>
      </el-form-item>

<!--      验证码-->
      <el-form-item>
        <div class="captcha-container">
        <el-input v-model="form.captcha"
                  placeholder="验证码"
                  :prefix-icon="Key"
                  maxlength="6"
                  class="form-input captcha-input"></el-input>
        <img :src="captcha" alt="验证码" title="点击刷新"
             class="captcha-img" @click="loadCaptcha">
        </div>
      </el-form-item>

<!--      登录按钮-->
      <el-form-item>
        <el-button class="login-btn" type="success" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>

<!--  页脚信息-->
    <div class="login-footer">
      <p>© 2023 抢票系统 版权所有</p>
    </div>
  </div>
</template>

<style scoped>

/* 基础布局 */
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

/* 背景样式 */
.login-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/back.jpg');
  background-size: cover;
  background-position: center;
  filter: blur(4px);
  z-index: 1;
}

.login-bg-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2;
}

/* 登录卡片 */
.login-card {
  position: relative;
  z-index: 3;
  width: 380px;
  margin: 0 auto;
  padding: 30px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  top: 50%;
  transform: translateY(-55%);
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.4);
}

/* 品牌区域 */
.login-brand {
  text-align: center;
  margin-bottom: 25px;
}

.brand-logo {
  width: 80px;
  height: 80px;
  object-fit: contain;
  margin-bottom: 15px;
  border-radius: 50%;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.brand-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 角色选择器 */
.role-selector {
  display: flex;
  margin-bottom: 25px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.role-item {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: #f9fafb;
}

.role-item:hover {
  background: #f0f2f5;
}

.role-active {
  background: #4096ff;
  color: white;
  font-weight: 500;
}

.role-icon {
  font-size: 18px;
}

/* 表单样式 */
.login-form {
  width: 100%;
}

.form-input {
  width: 100%;
  height: 45px;
  border-radius: 6px;
}

/* 验证码区域 */
.captcha-container {
  display: flex;
  gap: 10px;
}

/* 验证码输入框 */
.captcha-input {
  flex: 2;
  height: 45px;
}

/* 验证码图片：固定宽度，与输入框高度匹配 */
.captcha-img {
  flex: 1;
  height: 45px;
  width: 169px;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 150, 255, 0.3);
}

/* 辅助链接 */
.login-links {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.link-item {
  color: #4096ff;
  font-size: 14px;
  text-decoration: none;
  transition: color 0.2s;
}

.link-item:hover {
  color: #1677ff;
  text-decoration: underline;
}

/* 页脚信息 */
.login-footer {
  position: relative;
  z-index: 3;
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin-top: -30px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 20px;
  }

  .brand-title {
    font-size: 18px;
  }

  .role-label {
    font-size: 14px;
  }

  .captcha-img {
    width: 80px;  /* 小屏幕调整图片宽度 */
  }
}
</style>